import {Component, OnInit} from '@angular/core';
import {NzMessageService} from 'ng-zorro-antd';
import {UtilService} from "../../my-service/util.service";
import {Router, ActivatedRoute} from "@angular/router";
import {TrainingService} from "../../my-service/training.service";

@Component({
  selector: 'start-root',
  templateUrl: './start.component.html',
  styleUrls: ['./start.component.css'],
})
export class StartComponent implements OnInit {
  trainingID: string;
  userGuid: string;
  canJoin: boolean;
  classGuid: string;
  traingStatus: boolean;
  jumpUrl = 'clientcreativitytraining.lessonplan.cn';

  constructor(private message: NzMessageService,
              private utilServe: UtilService,
              private router: Router,
              private routerInfo: ActivatedRoute,
              private trainingService: TrainingService) {

  }

  getTrainingInfo(trainingID) {
    this.trainingService.getTrainingByID(trainingID).then(res => {
      if (res.status == 1) {
        this.classGuid = res.data[0].FK_ClassGuid;
        //判断当前测试状态
        if (res.data[0].Status == 1) {
          this.traingStatus = true;
        }
        if (this.traingStatus) {
          //当前测试未删除
          if (this.classGuid == 'null' || !this.classGuid) {
            //匿名测试
            this.canJoin = true;
          } else {
            //非匿名测试
            if (this.userGuid) {
              this.getStuJoinClass();
            } else {
              //非匿名测试没有登录跳转回登录
              window.location.href = 'http://clientpassport.lessonplan.cn/?returnURL=' + this.jumpUrl + '/home/start;id=' + this.trainingID;
            }
          }
        } else {
          //测试已经被删除
          this.message.error('该威廉斯量表创造力测试已经被删除，请选择新的测试进行测试');
        }
      }
    })
  }

  //获取学生加入班级列表
  getStuJoinClass() {
    this.trainingService.getJoinClass(this.userGuid).then(res => {
      if (res.status == 1) {
        res.data.forEach(val => {
          if (val.FK_ClassGuid == this.classGuid) {
            this.canJoin = true;
            return;
          }
        })
      }
    })
  }

  getUserInfo() {
    this.utilServe.getUserInfo().then(res => {
      if (res.status == 1) {
        this.userGuid = res.userGuid;
      }
      this.getTrainingInfo(this.trainingID);
    })
  }

  ngOnInit() {
    this.trainingID = this.routerInfo.snapshot.params.id;
    this.getUserInfo();
  }

  /*进入测试说明*/
  goTrainingExplain() {
    if (!this.trainingID) {
      this.message.error('请你通过扫码加入威廉斯量表创造力测试');
      return;
    }
    if (!this.traingStatus) {
      this.message.error('该威廉斯量表创造力测试已经被删除，请选择新的测试进行测试');
      return;
    }
    if (!this.canJoin) {
      this.message.error('请你先加入该花名册再进行该花名册的威廉斯量表创造力测试');
      return;
    }
    if (this.classGuid == 'null' || !this.classGuid) {
      this.classGuid = '';
    }
    this.router.navigate(['../explain', {ID: this.trainingID, classID: this.classGuid}], {relativeTo: this.routerInfo});
  }


}
